package cn.lingyangwl.agile.dynamic.config.core;

import cn.lingyangwl.agile.dynamic.config.model.*;
import cn.lingyangwl.agile.model.module.tenant.*;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author shenguangyang
 */
@Slf4j
@Component
@RabbitListener(bindings = {
    @QueueBinding(
//                value = @Queue(value = ResetIsvMchAppInfoConfigMQ.QUEUE, durable = "true"),
        value = @Queue(durable = "true"), key = RefreshConfigMQ.KEY, // 切记: 此处无需设置队列名称，否在得话，多个消费者只有一个消费者能消费数据。其它消费者无法消费数据
        exchange = @Exchange(value = RefreshConfigMQ.EXCHANGE, type = ExchangeTypes.FANOUT))
})
public class ConfigRefreshListener {
    @Resource
    private ConfigFactory configFactory;

    @RabbitHandler
    public void onMessage(String msg, Channel channel, Message message) {
        try {
            RefreshConfigMQ msgBody = RefreshConfigMQ.parse(msg, RefreshConfigMQ.class);
            log.info("tenantId: {}, bus message: {}", TenantContext.get().getTenantId(), msg);
            ConfigMsg payload = msgBody.getConfigMsg();
            payload.setTenantId(TenantContext.get().getTenantId());
            payload.setMainTenantId(TenantContext.get().getMainTenantId());
            configFactory.deleteConfig(payload);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}